package com.wonders.healthcitydoctor.ui.map;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;

import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.ui.base.BaseBackFragment;
import com.wonders.healthcitydoctor.util.LogUtil;
import com.wonders.healthcitydoctor.util.PointUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;

public class MapFragment extends BaseBackFragment implements AMap.OnMarkerClickListener, EasyPermissions.PermissionCallbacks {
    private static final String LATITUDE = "LATITUDE";
    private static final String LONGTIUDE = "LONGTIUDE";
    private static final String HOSNAME = "HOSNAME";

    @BindView(R.id.btn_driver)
    Button btnDriver;
    @BindView(R.id.btn_walk)
    Button btnWalk;
    private WeakReference<AMapLocationListener> ref;
    @BindView(R.id.map)
    MapView map;


    private double latitude;
    private double longitude;
    private String hosName;
    private MarkerOptions markerOption;
    private AMap aMap;
    private LatLng latlng = null;
    private Marker marker;

    public MapFragment() {
        // Required empty public constructor
    }

    public static MapFragment newInstance(double latitude, double longitude, String hosName) {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        args.putDouble(LATITUDE, latitude);
        args.putDouble(LONGTIUDE, longitude);
        args.putString(HOSNAME, hosName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            latitude = getArguments().getDouble(LATITUDE);
            longitude = getArguments().getDouble(LONGTIUDE);
            hosName = getArguments().getString(HOSNAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        ButterKnife.bind(this, view);
        map.onCreate(savedInstanceState);
        setTitle(view, "地图展示", "导航", 0);
        latlng = new LatLng(latitude, longitude);
        init();
        locationAndContactsTask();
        return view;
    }

    @Override
    public void setOnRightClickListener(View v) {
        super.setOnRightClickListener(v);
//        com.amap.api.maps.model.LatLng epoint = new com.amap.api.maps.model.LatLng(latitude, longitude);
//        Poi epoi = new Poi(hosName, epoint, "");
//        AmapNaviPage.getInstance().showRouteActivity(getContext().getApplicationContext(), new AmapNaviParams(epoi), this);

//        daoHang(latitude,longitude);
        if (latitude==0.0||longitude==0.0) {
          ToastMessageShort("医院地址获取失败！");
        }else if(curLatitude==0.0||curLongitude==0.0){
            ToastMessageShort("正在定位请稍后再试！");
        }else {
            ShowMap();
        }
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = map.getMap();
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latlng));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
            setUpMap();
        }
    }

    private void setUpMap() {
        aMap.setOnMarkerClickListener(this);
        addMarkersToMap();// 往地图上添加marker
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        map.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        map.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        map.onDestroy();
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {
        LogUtil.i("mapjwd", latitude + "," + longitude);
        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_RED))
                .position(latlng)
                .draggable(true)
                .title("地址：")
                .snippet(hosName);

        marker = aMap.addMarker(markerOption);

        marker.showInfoWindow();
    }

    /**
     * 对marker标注点点击响应事件
     */
    @Override
    public boolean onMarkerClick(final Marker marker) {
        if (aMap != null) {
            jumpPoint(marker);
        }
        ToastMessageShort(hosName);
//        com.amap.api.maps.model.LatLng epoint = new com.amap.api.maps.model.LatLng(latitude, longitude);
//        Poi epoi = new Poi(hosName, epoint, "");
//        AmapNaviPage.getInstance().showRouteActivity(getContext().getApplicationContext(), new AmapNaviParams(epoi), this);

//        daoHang(latitude,longitude);
        LogUtil.i("curLatitude", curLatitude + "");

        return true;
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = aMap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }


    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    private void ShowMap() {

        Intent intent;
        if (isInstallByread("com.autonavi.minimap")) {
            intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("androidamap://route?sourceApplication=健康城市" + "&dlat=" + latitude + "&dlon=" + longitude + "&dname=" + hosName + "&dev=0" + "&t=1"));
//            intent = Intent.getIntent("androidamap://navi?sourceApplication=&poiname="+hosName+"&lat:"+latitude+"&lon:"+longitude+"&dev=0");
            getContext().startActivity(intent);
        } else if (isInstallByread("com.baidu.BaiduMap")) {//传入指定应用包名
            double[] enBdPont = PointUtil.gaoDeToBaidu(longitude, latitude);
            try {
                intent = Intent.getIntent("intent://map/direction?" +
                        //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                        "destination=latlng:" + enBdPont[1] + "," + enBdPont[0] + "|name:" + hosName +        //终点
                        "&mode=driving&" +          //导航路线方式
                        "region=" +           //
                        "&src=#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                getContext().startActivity(intent); //启动调用
            } catch (URISyntaxException e) {
                Log.e("intent", e.getMessage());
            }
        } else {
            try {
                double[] startDPont = PointUtil.gaoDeToBaidu(curLongitude, curLatitude);
                double[] enDPont = PointUtil.gaoDeToBaidu(longitude, latitude);
                StringBuffer stringBuffer = new StringBuffer("http://api.map.baidu.com/direction?origin=")
                        .append(startDPont[1]).append(",").append(startDPont[0])
                        .append("&destination=") .append(enDPont[1]).append(",").append(enDPont[0])
                        .append("&mode=driving&region=shanghai&output=html&src=")
                        .append(hosName);
                intent = Intent.getIntent(stringBuffer.toString());
                //http://api.map.baidu.com/direction?origin=latlng:"+loc1.getStringLatLng()+"|name:"+loc1.getAddress()+"&destination=latlng:"+loc2.getStringLatLng()+"|name:"+loc2.getAddress()+"&mode=driving&src=重庆快易科技|CC房车-车主
                getContext().startActivity(intent);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
    }
}
